<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="changeValue"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="deptTree"
          node-key="id"
          :data="depts"
          :props="defaultPorps"
          default-expand-all
          :expand-on-click-node="false"
          highlight-current
          @current-change="selectNode"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="'add-employee'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button size="mini" @click="exportEmployee">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="list" style="width: 100%" stripe>
          <el-table-column prop="prop" align="center" type="selection" width="50" />
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template v-slot="{ row }">
              <el-avatar v-if="row.staffPhoto" :size="30" :src="row.staffPhoto" />
              <span v-else class="username"> {{ row.username.charAt(0) }} </span>
            </template>
          </el-table-column>
          <el-table-column prop="username" align="center" label="姓名" />
          <el-table-column prop="mobile" align="center" sortable label="手机号" />
          <el-table-column prop="workNumber" align="center" sortable label="工号" />
          <el-table-column prop="formOfEmployment" align="center" label="聘用形式">
            <template v-slot="{ row }">
              <span>{{ row.formOfEmployment===1?'正式':row.formOfEmployment===2?'非正式':'无' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" align="center" label="部门" />
          <el-table-column prop="timeOfEntry" align="center" sortable label="入职时间" />
          <el-table-column prop="prop" align="center" label="操作" width="280">
            <template v-slot="{ row }">
              <el-button type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button type="text" @click="btnRole(row.id)">角色</el-button>
              <el-popconfirm
                title="确定删除该条数据吗？"
                @onConfirm="confirmDel( row.id)"
              >
                <el-button slot="reference" type="text" style="margin-left:10px" size="mini">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row type="flex" justify="end" align="moddle" style="height:60px">
          <el-pagination
            layout="total, prev, pager, next"
            :total="total"
            @current-change="changePage"
          />
        </el-row>
      </div>
      <import-excel :show-excel-dialog.sync="showExcelDialog" @uploadSuccess="getEmployeeList" />
      <!-- 父组件接收上传成功 重新查询员工数据 -->
      <el-dialog title="分配角色" :visible.sync="dialogRole">
        <!-- 弹层显示 -->
        <el-checkbox-group v-model="roleIds">
          <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
        </el-checkbox-group>
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="mini" type="primary" @click="btnOKRole">确认</el-button>
            <el-button size="mini" @click="dialogRole=false">取消</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getDepartment } from '@/api/department'
import { transListToTreeData } from '@/utils'
import { exportEmployee, getEmployeeList, delEmployee, getRoleList, getEmployeeDetail, assignRole } from '@/api/employee'
import FileSaver from 'file-saver'
import ImportExcel from './components/import-excel.vue'
export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      currentId: null,
      showExcelDialog: false, // 控制excel的弹层显示和隐藏
      dialogRole: false, // 控制分配角色的弹层显示和隐藏
      depts: [], // 组织数据
      list: [], // 员工数据
      total: 0,
      defaultPorps: {
        label: 'name',
        children: 'children'
      },
      // 存储查询参数
      queryParams: {
        departmentId: null,
        page: 1, // 当前页码
        pagesize: 8,
        keyword: '' // 模糊搜索字段
      },
      roleList: [], // 获取角色列表
      roleIds: [] // 列表双向绑定
    }
  },
  created() {
    // console.log(getDepartment())
    this.getDepartment()
  },
  methods: {
    async getDepartment() {
      // 递归方法 将列表转化为树形
      // let result = await getDepartment()
      // this.depts = transListToTreeData(result,0) 可以简写如下
      this.depts = transListToTreeData(await getDepartment(), 0)
      // 调用递归方法
      // console.log(this.depts[0])
      this.queryParams.departmentId = this.depts[0].id
      // 获取初始节点
      // 树组件渲染是异步的 等到更新完毕
      this.$nextTick(() => {
        // 此时意味着树渲染完毕
        this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId)
      // 设置选中节点
      })
      // 这个时候参数，记录了id
      this.getEmployeeList()
    },
    // 切换部门
    selectNode(node) {
      this.queryParams.departmentId = node.id // 重新记录了参数
      this.queryParams.page = 1 // 设置为第一页
      this.getEmployeeList()
    },
    // 查询员工数据
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.queryParams)
      this.list = rows
      this.total = total
    },
    // 切换页码
    changePage(newValue) {
      this.queryParams.page = newValue // 赋值新页码
      this.getEmployeeList() // 重新查询数据
    },
    // 防抖处理 单位时间内只执行最后一次
    changeValue() {
      clearTimeout(this.timer) // 清理上一次的定时器
      // this的实例上赋值了一个timer的属性
      this.timer = setTimeout(() => { // 定时器
        this.queryParams.page = 1
        this.getEmployeeList()
      }, 500)
    },
    // 导出员工列表
    async exportEmployee() {
      const result = await exportEmployee() // 导出所有的员工接口
      // 使用一个npm包 直接将blob文件下载到本地 file-saver
      // FileSaver.saveAs(blob对象,文件名称)
      FileSaver.saveAs(result, '员工信息表.xlsx')
    },
    // 删除角色员工
    async confirmDel(id) {
      await delEmployee(id)
      if (this.list.length === 1 && this.queryParams.page > 1) this.queryParams.page--
      this.getEmployeeList()
      this.$message.success('删除员工成功')
    },
    // 分配角色按钮
    async btnRole(id) {
      this.roleList = await getRoleList()
      // console.log(this.roleList)
      this.currentId = id // 获取的id赋值
      // console.log(this.currentId)
      const { roleIds } = await getEmployeeDetail(id)
      this.roleIds = roleIds
      this.dialogRole = true
    },
    async btnOKRole() {
      await assignRole(
        {
          id: this.currentId,
          roleIds: this.roleIds
        }
      )
      this.$message.success('分配角色成功')
      this.dialogRole = false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>
